import {RequestConfig} from '@/libs/config'
import {RequestCore} from './RequestCore'

declare interface SmartAjaxResult {
    code?: number
    message?: string
    data?: any
    time?: string
}


// 封装在请求方法
export class RequestUtil {
    static getAjax(url: string, params = {}, key: string | number = null): Promise<SmartAjaxResult> {
        const u = key ? `${url}/${key}` : url
        return new RequestCore().instance.get(u, {params})
    }

    // 用于新增数据
    static postAjax(url: string, data = {}): Promise<SmartAjaxResult> {
        return new RequestCore().instance.post(url, data)
    }

    // 用于修改数据
    static putAjax(url: string, data = {}, key: string | number = null): Promise<SmartAjaxResult> {
        const URI = key ? `${url}/${key}` : url
        return new RequestCore().instance.put(URI, data)
    }

    // 用于删除数据
    static delAjax(url: string, data: Array<string | number> = []): Promise<SmartAjaxResult> {
        return new RequestCore().instance.delete(url, {data})
    }

    // 用于上传文件
    static uploadAjax(url: string, formData, callback = null): Promise<SmartAjaxResult> {
        const config = {
            timeout: 60 * 1000 * 2,
            headers: {'content-type': RequestConfig.uploadContentType},
            onUploadProgress: callback ? progressEvent => callback(progressEvent) : undefined,
        }

        return new RequestCore().instance.post(url, formData, config)
    }
}
